<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并确认',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createByName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="单据单号" prop="deliveryBillNo">
              <ElInputBox :data="form" dataName="deliveryBillNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="发货类型" prop="deliveryType">
              <ElSelectBox :data="form" dataName="deliveryType" :options="[
                {
                  label: '成品发货',
                  value: 1,
                },
                {
                  label: '半成品发货',
                  value: 2,
                }
              ]" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="客户名称" prop="customerCode" isRules>
              <ElSelectBox :data="form" dataName="customerCode" placeholder="请选择" :options="options.customer"
                :disabled="!isEdit" @changeBtn="selectCustomer" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <template v-if="form.customerCode">
          <CellBox title="快递信息" isTop>
            <div class="expressDelivery list-r-12 dlText-90">
              <SenderAddress :data="form" :isEdit="isEdit" />
              <ReceiverAddress :data="form" :isEdit="isEdit" />
            </div>
          </CellBox>
          <CellBox title="其他信息" isTop>
            <FlexBox>
              <ElFormItemBox label="发货时间" prop="expressTime" isRules>
                <ElDayBox :data="form" dataName="expressTime" :disabled="!isEdit" />
              </ElFormItemBox>
              <ElFormItemBox label="收货方式" prop="receivingWay" isRules>
                <ElSelectBox :data="form" dataName="receivingWay" :options="options.receivingWay" :disabled="!isEdit" />
              </ElFormItemBox>
              <ElFormItemBox label="快递方式" prop="expressWay">
                <ElSelectBox :data="form" dataName="expressWay" :options="options.expressWay" :disabled="!isEdit" />
              </ElFormItemBox>
              <ElFormItemBox label="快递单号" prop="expressBillNo">
                <ElInputBox :data="form" dataName="expressBillNo" :disabled="!isEdit" />
              </ElFormItemBox>
              <ElFormItemBox label="快递费用" prop="expressCost">
                <ElNumberBox :data="form" dataName="expressCost" unit="元" :disabled="!isEdit" />
              </ElFormItemBox>
              <ElFormItemBox label="费用归属" prop="courierFeeType" isRules>
                <ElSelectBox :data="form" dataName="courierFeeType" :options="proxy.$optionsArr.courierFeeType"
                  :disabled="!isEdit" />
              </ElFormItemBox>
              <ElFormItemBox label="付费方式" prop="paymentWay">
                <ElSelectBox :data="form" dataName="paymentWay" :options="options.paymentWay" :disabled="!isEdit" />
              </ElFormItemBox>
              <ElFormItemBox label="费用部门" prop="costAssumeDepartment">
                <ElSelectBox :data="form" dataName="costAssumeDepartment" :options="options.costAssumeDepartment"
                  :disabled="!isEdit" />
              </ElFormItemBox>
              <ElFormItemBox label="总公斤数" prop="expressGoodsWeight">
                <ElNumberBox :data="form" dataName="expressGoodsWeight" unit="kg" :disabled="!isEdit" />
              </ElFormItemBox>
              <ElFormItemBox label="总件数" prop="expressGoodsCount">
                <ElNumberBox :data="form" dataName="expressGoodsCount" unit="件" :disabled="!isEdit" />
              </ElFormItemBox>
              <ElFormItemBox label="单据备注" prop="deliveryRemark" class="wAuto">
                <ElInputBox :data="form" dataName="deliveryRemark" type="textarea" :disabled="!isEdit" />
              </ElFormItemBox>
            </FlexBox>
          </CellBox>
          <CellBox title="单据明细" isTop>
            <TableBoxMx :data="{
              disabled: !isEdit,
              tbody: form.detailList,
              columnKey: 'productNo',
              isColumn: ['productName', 'productSpecificationName', 'productVersion'],
              thead: [
                {
                  label: '产品名称',
                  prop: 'productName',
                  align: 'left',
                  width: null,
                },
                {
                  label: '产品型号',
                  prop: 'productSpecificationName',
                  align: 'center',
                  width: 160,
                },
                {
                  label: '版本',
                  prop: 'productVersion',
                  align: 'center',
                  width: 60,
                },
                {
                  label: '协议书号',
                  prop: 'xieYiShuHao',
                  align: 'center',
                  width: 220,
                  formType: 'select',
                  formProp: 'detailList',
                  options: saleOrdersArr,
                  labelName: 'xieYiShuHao',
                  valueName: 'xieYiShuHao',
                  changeBtn: (value: string, row: any, rows: any) => {
                    const _row = rows[0] || {}
                    setOrder(row, _row)
                  }
                },
                {
                  label: '印刷版面',
                  prop: 'productLayout',
                  align: 'center',
                  width: 140,
                },
                {
                  label: '发货数量',
                  prop: 'deliveryQuantity',
                  align: 'center',
                  width: 120,
                  formProp: 'detailList',
                  formType: 'number',
                },
                {
                  label: '单位',
                  prop: 'productUnit',
                  align: 'center',
                  width: 60,
                },
                {
                  label: '生产日期',
                  prop: 'produceDate',
                  align: 'center',
                  width: 160,
                  formProp: 'detailList',
                  formType: 'day',
                },
                {
                  label: '备注',
                  prop: 'deliveryMxRemark',
                  align: 'left',
                  width: 260,
                  formType: 'text',
                },
              ],
              //表格-列表搜索
              operation: [
                {
                  label: '复制',
                  icon: 'CopyDocument',
                  click: (row: any, rowIndex: number) => {
                    const _row = {
                      productName: row.productName,
                      productSpecificationName: row.productSpecificationName,
                      productVersion: row.productVersion,
                      productNo: row.productNo,
                    }
                    form.detailList.splice(rowIndex + 1, 0, _row)
                  }
                },
                {
                  label: '删除',
                  icon: 'Delete',
                },
              ],
              add: () => {
                pupAdd.state = true
                getAddTbody()
              },
            }">
            </TableBoxMx>
          </CellBox>
        </template>
      </div>
    </template>
  </DetailsFormBox>
  <SelectCom :pup="pupAdd" :table="pupAdd.tableAdd" isCheckbox :selectable="(row: any) => {
    const _arr = data.form.detailList.map((el: any) => el.productNo)
    return !_arr.includes(row.productSpecificationCode)
  }" @searchBtn="getAddTbody" @selectBtn="(arr: any) => {
    const _arr = arr.map((el: any) => ({
      productName: el.productName,
      productSpecificationName: el.productSpecificationName,
      productVersion: el.productVersion,
      productNo: el.productSpecificationCode,
    }))
    data.form.detailList.push(..._arr)
  }">
    <template #search="{ search }">
      <ElFormItemBox label="产品名称" prop="productName">
        <ElInputBox :data="search" dataName="productName" />
      </ElFormItemBox>
    </template>
    <template #saleOrders="{ row }">
      {{row.saleOrders.map((el: any) => `${el.xieYiShuHao}【${el.waitDeliveryQuantity}${el.productUnit}】`).join('、')}}
    </template>
  </SelectCom>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import SenderAddress from '../template/SenderAddress.vue'; // 寄方信息
import ReceiverAddress from '../template/ReceiverAddress.vue'; // 收方信息
import { useListComponent } from '../pageTs.ts'; // 引入逻辑
const { dataInfo, options } = useListComponent();
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    deliveryType: 1, // 基本信息-发货类型：1成品发货，其他待定
    customerCode: "", // 基本信息-客户编码
    companyName: "", // 寄方信息-寄方公司名称
    senderName: "", // 寄方信息-寄方姓名
    senderTelephone: "", // 寄方信息-寄方电话
    provinceCode: "", // 寄方信息-寄方省编码
    cityCode: "", // 寄方信息-寄方市编码
    areaCode: "", // 寄方信息-寄方区编码
    address: "", // 寄方信息-寄方详细地址
    receivingWay: "", // 其他信息-收货方式（字典明细项）
    expressWay: "", // 其他信息-送货方式（快递公司）（字典明细项）
    expressBillNo: "", // 其他信息-快递单号
    expressTime: "", // 其他信息-快递时间（送货时间）
    expressCost: null, // 其他信息-快递费用
    paymentWay: "", // 其他信息-付款方式（字典明细项）
    costAssumeDepartment: "", // 其他信息-费用承担部门
    expressGoodsWeight: null, // 其他信息-快递物品重量（公斤数）
    expressGoodsCount: 0, // 其他信息-快递物品件数
    deliveryRemark: "", // 发货备注
    receiveAddressCode: "", // 收方信息-收货人编码（收货地址代码）
    receiveCompanyName: "", // 收方信息-收方公司名称
    receiverName: "", // 收方信息-收方姓名
    receiveTelephone: "", // 收方信息-收方电话
    receiveProvinceCode: "", // 收方信息-收方省编码
    receiveCityCode: "", // 收方信息-收方市编码
    receiveAreaCode: "", // 收方信息-收方区编码
    receiveAddress: "", // 收方信息-收方详细地址
    courierFeeType: 0, // 快递费用归属，0-客户承担；1-公司承担；2-各自一半，默认0
    fhMxList: [], // 发货明细数据存储集合对象
    associationOrderNo: "", // 关联业务订单号（SaleOrder.SaleOrderCode）
    productNo: "", // 成品代码(ProductSpecification.ProductSpecificationCode)
    deliveryBoxCount: 0, // 发货箱数
    deliveryQuantity: 0, // 发货数量
    deliveryMxRemark: "", // 发货明细备注
    orderProductSpecificationCode: "", // 订单型号编码(OrderProductSpecification.OrderProductSpecificationCode)
    kilogramQuantity: null, // 公斤数
    produceDate: "", // 生产日期
    detailList: []
  },
});
const isEdit = ref(true)
//选择客户
const selectCustomer = (isInitialized: boolean = false) => {
  const _form = data.form
  getProductOrder()//获取客户产品信息
  //初始化
  if (isInitialized) {
    const _keyArr = [
      "companyName",
      "senderName",
      "senderTelephone",
      "address",
      "receiveCompanyName",
      "receiverName",
      "receiveTelephone",
      "receiveAddress",
    ]
    for (const k in _keyArr) {
      _form[_keyArr[k]] = ''
    }
    _form.detailList = []
  }
}
//获取明细协议书号下拉数据
const saleOrdersArr = (row: any) => {
  let _arr: any = []
  if (options.product.length > 0) {
    const _productArr = options.product.find((find: any) => find.productSpecificationCode === row.productNo)?.saleOrders || []
    _arr = _productArr.map((el: any) => ({
      ...el,
    }))
  }
  return _arr
}
//获取成品信息
const getAddTbody = () => {
  const _table = pupAdd.tableAdd
  _table.tbody = proxy.$filterArr(options.product, (row: any) => {
    return row.productName.includes(_table.search.productName)
  })
}
const pupAdd: any = reactive({
  state: false,
  typeName: 0,
  title: `选择成品`,
  tbody: [],
  tableAdd: {
    rowKey: 'productSpecificationCode',
    search: {
      productName: '',
    },
    tbody: [],
    thead: [
      {
        label: '成品名称',
        prop: 'productName',
        align: 'left',
        width: 400,
      },
      {
        label: '型号规格',
        prop: 'productSpecificationName',
        align: 'left',
        width: 120,
      },
      {
        label: '产品版本',
        prop: 'productVersion',
        align: 'center',
        width: 80,
      },
      {
        label: '库存数量',
        prop: 'stockQuantity',
        align: 'center',
        width: 140,
      },
      {
        label: '单位',
        prop: 'productUnit',
        align: 'center',
        width: 120,
      },
      {
        label: '待发货订单',
        prop: 'saleOrders',
        align: 'left',
        width: null,
      },
    ],
  },
});
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();

//获取数据
const getForm = async () => {
  const _query: any = route.query
  setLoading()
  //是否新建
  if (!!!_query.code) {
    data.loading = false
    return
  }
  proxy.$api.OrderBusniess.GetSaleOrderDeliveryDetail({
    queryBy: 0,
    queryValue: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = ['1', '2'].includes(_query.type)
      data.form = res
      selectCustomer()
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
//获取客户产品信息
const getProductOrder = () => {
  proxy.$api.OrderBusniess.GetSaleOrderDeliveryMxByCustomerCode({
    queryBy: 0,
    queryValue: data.form.customerCode,
  })
    .then((res: any) => {
      options.product = proxy.$flattenObjectArray(res.products, 'productSpecifications', (row: any) => ({
        ...row,
        saleOrders: row.saleOrders.map((el: any) => ({
          ...el,
          cartonWeight: row.cartonWeight,//包装信息-每个纸箱重量
          eachWeight: row.eachWeight,//包装信息-每个（套）标签重量
          eachBoxQuantity: row.eachBoxQuantity,//包装信息-每箱数量
          productUnit: row.productUnit,//产品单位
          productVersion: row.productVersion,//产品版本
        }))
      }))
    })
    .catch(() => {

    });
};


//设置明细的订单信息
const setOrder = (rowA: any, rowB: any) => {
  rowA.productLayout = rowB.productLayout//印刷版面
  rowA.deliveryQuantity = rowB.waitDeliveryQuantity//发货数量
  rowA.productUnit = rowB.productUnit//产品单位
  rowA.produceDate = rowB.productionDate//生产日期
  rowA.saleOrderGroupNumber = rowB.saleOrderGroupNumber//订单单号
  rowA.orderProductSpecificationCode = rowB.orderProductSpecificationCode//订单产品型号code
  rowA.associationOrderNo = rowB.saleOrderCode//成品代码(ProductSpecification.ProductSpecificationCode)
};

const saveBtn = (form: any, isConfirm: boolean = false) => {
  const _form: any = {
    ...form,
    fhMxList: form.detailList.map((el: any) => (
      {
        associationOrderNo: el.associationOrderNo || '', //关联业务订单号（SaleOrder.SaleOrderCode）
        productNo: el.productNo || '', //成品代码(ProductSpecification.ProductSpecificationCode)
        deliveryBoxCount: el.deliveryBoxCount || '', //发货箱数
        deliveryQuantity: el.deliveryQuantity || '', //发货数量
        deliveryMxRemark: el.deliveryMxRemark || '', //发货明细备注
        orderProductSpecificationCode: el.orderProductSpecificationCode || '', //订单型号编码(OrderProductSpecification.OrderProductSpecificationCode)
        kilogramQuantity: el.kilogramQuantity || '', //公斤数
        produceDate: el.produceDate || '', //公斤数
      }
    ))
  }
  // return
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.OrderBusniess.CreateSaleOrderDelivery(_form)
        .then((res: any) => {
          if (isConfirm) {
            _setState(res)
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;
    case '2'://编辑
      proxy.$api.OrderBusniess.UpdateSaleOrderDelivery(_form)
        .then((res: any) => {
          if (isConfirm) {
            _setState(_form)
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;
    default:
      break;
  }
  function _sun() {
    closeBtn('保存成功')
  }
  function _setState(row: any) {
    proxy.$api.OrderBusniess.SureSaleOrderDelivery({
      entityID: row.deliveryID, //
    })
      .then((res: any) => {
        _sun()
      })
      .catch(() => {
        _sun()
      });
  }
};
const closeBtn = (message?: string) => {
  if (message) {
    proxy.$message(message)
  }
  sendMsg('save', true);
  // getForm()
  window.close();
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};
import { getCustomer, getDictionary, getOrganization } from '@/utils/optionsArr.ts';
onMounted(() => {
  getForm();
  //客户
  getCustomer(options, 'customer');
  //收货方式
  getDictionary(options, 'receivingWay', {
    DictionaryCode: 'ReceivingType',
  });
  //快递方式
  getDictionary(options, 'expressWay', {
    DictionaryCode: 'SendingType',
  });
  //付费方式
  getDictionary(options, 'paymentWay', {
    DictionaryCode: 'LogisticsPaidType',
  });
  //费用部门
  getOrganization(options, 'costAssumeDepartment');
});
</script>
